import { ref } from 'vue'
import { downLoadFile } from '@r/api/file'

export function useDownload() {
  const multiloading = ref(false)
  let finishCount = ref(0)
  function limitLoad(paths: any[], handler: any, limit: number) {
    // 对数组做一个拷贝
    const sequence = [...paths];
    let promises: any[] = [];
    //并发请求到最大数
    promises = sequence.splice(0, limit).map((url, index) => {
      // 这里返回的 index 是任务在 promises 的脚标，用于在 Promise.race 之后找到完成的任务脚标
      return handler(url).then(() => {
        return index;
      });
    });

    // 利用数组的 reduce 方法来以队列的形式执行
    return sequence.reduce((last, _paths, currentIndex) => {
      return last.then(() => {
        // 返回最快改变状态的 Promise
        finishCount.value = finishCount.value + 1
        return Promise.race(promises)
      }).catch((err: any) => {
        // 这里的 catch 不仅用来捕获前面 then 方法抛出的错误
        // 更重要的是防止中断整个链式调用
        console.error(err)
      }).then((res: any) => {
        // 用新的 Promise 替换掉最快改变状态的 Promise
        promises[res] = handler(sequence[currentIndex]).then(() => {
          return res
        });
      })
    }, Promise.resolve()).then(() => {
      return Promise.all(promises)
    })
  }
  function getFileBolob(url: string) {
    const fileName = url.slice(url.lastIndexOf('/') + 1)
    return downLoadFile(url, fileName)
  }
  function onMultiDownload(pathList: string[]) {
    if (pathList.length === 0) {
      return
    }
    multiloading.value = true
    // handleZip(id, pathList)
    limitLoad(pathList, getFileBolob, 3)
      .then(() => {
        multiloading.value = false
        finishCount.value = 0
      })
  }
  return {
    finishCount,
    multiloading,
    onMultiDownload
  }
}